1

在具有一些可拖动图像的 html 页面上,我们必须使用鼠标指针绘制形状或线条,绘制图像和形状已完成,但不能在可拖动图像上。此外,如果用户移动图像,则先前绘制的形状应保持原样
。同时,我已经能够创建形状和画线,但是当我尝试
在图像上画线时,它又回到了背景中。有人可以建议我如何使用
当前也在使用的画布和 html5 来实现相同的目标。

4

1 回答 1

0

一种方法是创建一个函数来绘制您的图像和与该图像关联的形状

您可以通过使用与图像偏移相同的偏移绘制形状来保持图像及其形状的协调。因此,如果您在 [x,y] 处绘制图像,则将 x & y 添加到形状中的每个点:

// points[] is an array of points that defines the shape you
// want drawn on your image

function drawImageWithShapes(img,points,x,y){
    ctx.drawImage(img,x,y);
    ctx.beginPath();
    ctx.moveTo(points[0].x+x,points[0].y+y);
    for(var i=1; i<points.length;i++){
        ctx.lineTo(points[i].x+x,points[i].y+y);
    }
    ctx.stroke();
}

在此处输入图像描述在此处输入图像描述

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

ctx.lineWidth=4;
ctx.strokeStyle='red';

var x=50;
var y=50;

var points=[];
points.push({x:37,y:0});
points.push({x:75,y:75});
points.push({x:0,y:75});
points.push({x:37,y:0});


var img=new Image();
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/sun.png";
function start(){
  drawImageWithShapes(img,points,x,y);
}

function drawImageWithShapes(img,points,x,y){
  ctx.drawImage(img,x,y);
  ctx.beginPath();
  ctx.moveTo(points[0].x+x,points[0].y+y);
  for(var i=1; i<points.length;i++){
    ctx.lineTo(points[i].x+x,points[i].y+y);
  }
  ctx.stroke();
}

$('#test').click(function(){
  x+=10;
  y+=10;
  ctx.clearRect(0,0,cw,ch);
  drawImageWithShapes(img,points,x,y);

});
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id=test>Move and Redraw</button><br><br>
<canvas id="canvas" width=300 height=300></canvas>

于 2014-10-22T16:10:07.093 回答