在 Canvas 中我创建了一个二维上下文。在那种情况下......有一个功能......我能够创建一些“圆形对象”。现在,我想要的是获取单个圆形对象的 ImageData,而不是整个上下文的图像数据。
在下面的代码中,您可以看到我的愿望被注释掉了。
var c = document.getElementById('canvas');
var ctx = c.getContext('2d');
var circle = function (X,Y) {
var that = this;
that.X = X;
that.Y = Y;
that.clicked = function(e) {
//
//
//!!!!!!!!!!!!!!
// Code below works fine, on context level
imgData = ctx.getImageData(e.pageX, e.pageY, 1, 1);
//
// Code below is at the level of the circle, that's what I want, but isn't working
imgData = that.getImageData(e.pageX, e.pageY, 1, 1);
//!!!!!!!!!!!!!!
//
//
alert(imgData.data[3]);
}
that.draw = function () {
ctx.save();
ctx.translate(that.X, that.Y);
ctx.fillStyle = '#33cc33';
ctx.beginPath();
ctx.arc(0, 0, 50, 0, 2 * Math.PI);
ctx.fill();
ctx.stroke();
ctx.restore();
}
}
var circles = new Array();
circles.push(new circle(50,50));
document.addEventListener('click',function() {
circles.forEach(function(circ,index){
circ.clicked();
});
})
那么,如何获取特定对象的图像数据呢?
编辑: 我知道我需要先画圆,稍后在我的代码中这样做,但是如果我在上下文中有一个背景矩形,当我在圆旁边单击时,它将获得背景矩形的 imageData ,当我想返回 alpha rgba 的 0 值时。
最佳答案
为此,您需要将所有绘图记录为“阴影 Canvas ”。最常见的方法是创建形状对象并将它们存储在例如数组中:
- 在 Canvas 上绘制形状
- 记录它的类型、位置、尺寸、颜色和方向并存储为一个对象并将该对象推送到数组
当您需要将孤立的形状或对象作为图像获取时:
- 获取鼠标位置(如果你想点击对象来选择它)
- 遍历对象数组以查看哪个对象被“命中”
- 创建该形状尺寸的临时 Canvas
- 在临时 Canvas 中绘制形状
- 将数据提取为图像(
ctx.getImageData(x, y, w, h)
或canvas.toDataURL()
)
当您需要调整 Canvas 大小时,您只需遍历所有对象并重新绘制它们。您甚至可以使用此方法序列化数据进行存储。
一个对象的例子可以是:
function Rectangle(x, y, w, h, fill, stroke) {
this.x = x;
this.y = y;
this.width = w;
this.height = h;
this.fill = fill;
this.stroke = stroke;
}
您可以扩展此对象以将其自身渲染到 Canvas 上,并为您提供一个与其他形状隔离的位图。将此添加到上面的代码中:
Rectangle.prototype.render = function(ctx) {
if (this.fill) { /// fill only if fill is defined
ctx.fillStyle = this.fill;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
if (this.stroke) { /// stroke only if stroke is defined
ctx.strokeStyle = this.stroke;
ctx.strokeRect(this.x, this.y, this.width, this.height);
}
}
Rectangle.prototype.toBitmap = function() {
var tcanvas = document.createElement('canvas'), /// create temp canvas
tctx = tcanvas.getContext('2d'); /// temp context
tcanvas.width = this.width; /// set width = shape width
tcanvas.height = this.height;
tctx.translate(-this.x, -this.y); /// make sure shape is drawn at origin
this.render(tcxt); /// render itself to temp context
return tcanvas.toDataURL(); /// return image (or use getImageData)
}
您只需绘制形状,根据位置等创建对象:
var rect = new Rectangle(x, y, w, h, fillColor, strokeColor);
myShapeArray.push(rect);
当你需要渲染形状时:
for(var i = 0, shape; shape = myShapeArray[i++];)
shape.render(ctx);
而当你需要获取它的位图时(你预先用鼠标点击检索它的索引):
var image = myShapeArray[index].toBitmap();
当然:您可以为圆、线等制作类似的对象。
希望这对您有所帮助!
关于javascript - 如何获取特定对象的图像数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21680038/