【发布时间】:2015-06-17 07:54:51
【问题描述】:
下午好,
我是 HTML 5 中的 Canvas 以及将其与 Javascript 一起使用的新手。但我可以看到这真的很强大,我需要帮助。我已经进行了搜索,但找不到明确的答案。也许这里有人可以提供帮助。
我在 Canvas 上创建了一个带有背景图像的上下文。现在,我想裁剪或复制包含在多边形数据中的该图像的一部分,并将其放置在屏幕上的其他位置。我知道如何创建背景图像。我知道如何在该图像上创建一个多边形,并且我知道如何将图像数据复制到屏幕的另一部分。
那么我将如何复制该多边形内的所有图像数据/像素?有一个简单的方法吗?在此先感谢您的帮助。非常感谢。
编辑: 这是我正在尝试做的一个例子: http://jsfiddle.net/MFELx/
//I have no code, but it wouldn't let me post link. Hope this is allowed.
只有我试图在没有外部库或没有 JQUERY 的情况下这样做。我希望这更有意义。再次感谢您的帮助!
再次编辑:解决方案:
好的,所以 Mark E 的解决方案奏效了。我为那些没有 JQUERY 感兴趣的人编辑了它:
HTML:
复制多边形
原始背景
CSS:
body{ background-color: ivory; }
#canvas{border:1px solid red;}
JS:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var polygonData=[];
polygonData.push({x:125,y:75});
polygonData.push({x:100,y:118});
polygonData.push({x:50,y:118});
polygonData.push({x:25,y:75});
polygonData.push({x:49,y:31});
polygonData.push({x:100,y:31});
polygonData.push({x:125,y:75});
var img=new Image();
img.onload=start;
img.src='https://dl.dropboxusercontent.com/u/139992952/multple/stars1.png';
function start(){
// draw the original background
ctx.drawImage(img,0,0);
// copy the existing polygon to its new position
}
function copyPolygon(newStartingX,newStartingY){
// calculate the copy's offset versus the original
var dx=newStartingX-polygonData[0].x;
var dy=newStartingY-polygonData[0].y;
// define the path of the new polygon
ctx.beginPath();
ctx.moveTo(polygonData[0].x+dx,polygonData[0].y+dy);
for(var i=1;i<polygonData.length;i++){
ctx.lineTo(polygonData[i].x+dx,polygonData[i].y+dy);
}
ctx.closePath();
// clip to the path of the new polygon
ctx.save();
ctx.clip();
// use the clipping version of drawImage to
// redraw the existing canvas over the new polygon position
// Note: with clipping, new pixels will only be drawn in the new polygon
ctx.drawImage(canvas, 0,0,cw,ch, dx,dy,cw,ch);
// clean up -- un-clip by resetting the context state
ctx.restore();
}
function myFunction() {
copyPolygon(250,75);
}
【问题讨论】:
标签: html canvas copy polygon pixel