用旋转平移xy运动的公式

时间:2016-12-01 18:33:56

标签: image canvas rotation drag

我有一个canvas元素,我用context.rotate();

旋转

当我在画布中拖动图像时如果我旋转让我们说90度,我向左移动,图像向下移动,

是否有一个公式,我可以应用一个运动 例如 x + 5 y + 2 *度

我得到了真正的动作,我需要做的是将旋转的画布向我想要的方向移动?我想把它应用到这个有效的功能,但是有一个不希望的向左移动和图像向下移动的效果“

vm.canvasMouseMove = function (event) {
        vm.delta = Date.now();
        if (vm.mouseisdown && vm.delta - vm.now > (1000 / 60) && (event.clientX > 0 && event.clientY > 0)) {
            vm.now = vm.delta
            vm.snapshot.mouse.x -= event.clientX;
            vm.snapshot.offsetSlider.value -= vm.snapshot.mouse.x;
            if (vm.snapshot.offsetSlider.value < -160) {
                vm.snapshot.offsetSlider.value = -160
            }
            else if (vm.snapshot.offsetSlider.value > 160) {
                vm.snapshot.offsetSlider.value = 160
            }

            vm.snapshot.mouse.y -= event.clientY;
            vm.snapshot.verticalOffsetSlider.value += vm.snapshot.mouse.y;
            if (vm.snapshot.verticalOffsetSlider.value < -120) {
                vm.snapshot.verticalOffsetSlider.value = -120
            }
            else if (vm.snapshot.verticalOffsetSlider.value > 120) {
                vm.snapshot.verticalOffsetSlider.value = 120
            }
            vm.snapshot.mouse.x = event.clientX;
            vm.snapshot.mouse.y = event.clientY;
        }
    };`

这绘制

ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.rotate(vm.snapshot.rotationSlider.value * Math.PI / 180);
ctx.drawImage(image, vm.snapshot.offsetSlider.value - (canvas.width / 2), (vm.snapshot.verticalOffsetSlider.value * -1) - (canvas.height / 2), vm.scaledImageW * vm.snapshot.zoomSlider.value / 100, vm.scaledImageH * vm.snapshot.zoomSlider.value / 100);
ctx.rotate(-1 * vm.snapshot.rotationSlider.value * Math.PI / 180);
ctx.translate(-canvas.width / 2, -canvas.height / 2);
vm.donePicture = canvas.toDataURL();

1 个答案:

答案 0 :(得分:0)

这就是诀窍,将偏移传递给translate方法,然后仅考虑画布半翻译来绘制图像

ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.save();
    ctx.translate((canvas.width / 2) + (vm.snapshot.offsetSlider.value), (canvas.height / 2) - vm.snapshot.verticalOffsetSlider.value);
    ctx.rotate(vm.snapshot.rotationSlider.value * Math.PI / 180);
    ctx.drawImage(vm.canvasImage, 0 - (canvas.width/2), 0 - (canvas.height/2), vm.scaledImageW * vm.snapshot.zoomSlider.value / 100, vm.scaledImageH * vm.snapshot.zoomSlider.value / 100);
    ctx.restore();