使用鼠标在html5画布中水平和垂直倾斜绘图 [英] Skew the drawing horizontally and vertically in html5 canvas using mouse

查看:345
本文介绍了使用鼠标在html5画布中水平和垂直倾斜绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,我将图片加载到canvas元素。然后,我需要拖动,调整大小,旋转和偏斜。我设法实现拖动和调整大小。如何在这段代码上使用鼠标实现偏斜?我阅读了有关此主题的有用文章( http:// www.subshel​​l.com/en/subshel​​l/blog/image-manipulation-html5-canvas102.html )。我发现fabricjs插件,但它只工作一个图像,没有拖动。例如: http://fabricjs.com/matrix-transformation/
如果您将使用转换函数:

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);

这将转换分配给canvas元素的所有图像对象。我只想选择所选图片。

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

我的代码:

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

推荐答案

这里有一个更新的小提琴,可让您按Shift键单独倾斜任何图片单击其中一个角柄。

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.

诀窍在于使用 ctx.save() )调用周围的 ctx.restore()确保变换(和任何其他属性更改)仅适用于 save restore 之间。

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.

以下是主要变化:

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();
}

这篇关于使用鼠标在html5画布中水平和垂直倾斜绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆