Skew the drawing horizontally and vertically in html5 canvas using mouse

别来无恙 提交于 2019-12-25 04:31:23

问题


In my code I am loading images to canvas element. Then I need to drag, resize, rotate and skew it. I managed to implement both dragging and resizing. How can I implement skew using mouse on this code? I read a helpful article on this subject (http://www.subshell.com/en/subshell/blog/image-manipulation-html5-canvas102.html). I found fabricjs plugin, but it work only one image and without drag. For example: http://fabricjs.com/matrix-transformation/ . If you will use the transform function:

ctx.transform(1, 0.5, -0.5, 1.2, 30, 60);

This will transform all image objects assigned to the canvas element. I would like only the selected image.

My code:

https://jsfiddle.net/sjLnqk5d/2/


回答1:


Here's an updated fiddle that allows you to skew any image individually by pressing Shift when clicking one of the corner handles. You may need to tweak it a little bit to have the movements appear a bit more intuitive.

The trick is indeed in using ctx.save() and ctx.restore() around the ctx.transform() call, which makes sure that the transformation (and any other property changes) only applies between the save and restore.

Here are the key changes:

Shape.prototype.draw:

...
var skewX = this.skewX;
var skewY = this.skewY;
imgNew.onload = function(){ 
    ctx.save();
    ctx.transform(1, skewX/100, skewY/100, 1, 0, 0);
    ctx.drawImage(imgNew, locx, locy, width, height);
    ctx.restore();
}


来源:https://stackoverflow.com/questions/32922237/skew-the-drawing-horizontally-and-vertically-in-html5-canvas-using-mouse

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