HTML5 Canvas putImageData, translate it, change Image

北城余情 提交于 2019-12-01 08:38:54

问题


I want to draw an image using a HTML5 canvas, translate the image and then change the image but keep the transformations I've made. Is this possible?

Here's some pseudo-code to illustrate my problem:

// initially draw an image and translate it
var context = canvas.getContext("2d");
context.putImageData(someData, 0, 0);
context.translate(200, 10);


// then later somewhere else in code
// this should be drawn @ 200/10
var context = canvas.getContext("2d");
context.putImageData(someOtherData, ?, ?);

I thought this would be possible by some save/restore calls but I did not succeed yet, so how can I achieve this?


回答1:


The problem here is that putImageData is not affected by the transformation matrix.

This is by the Spec's orders:

The current path, transformation matrix, shadow attributes, global alpha, the clipping region, and global composition operator must not affect the getImageData() and putImageData() methods.

What you can do is putImageData to an in-memory canvas, and then

inMemCtx.putImageData(imgdata, 0, 0);
context.drawImage(inMemoryCanvas, x, y)

onto your regular canvas, and the translation will be applied to the drawImage call.




回答2:


Put the image and its associated data in a custom data structure. For instance:

var obj = {
    imgData: someData,
    position: [0, 0],
    translate: function (x, y) {
        this.position[0] = x;
        this.position[1] = y;
    }
};

Now you can do successive updates to both imgData and its position. Use obj.position[0] and obj.position[1] as xy-coordinates when drawing.

obj.translate(200, 10);


来源:https://stackoverflow.com/questions/11849114/html5-canvas-putimagedata-translate-it-change-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!