我正在使用画布加载图像。在图像上画一些线条。然后我想点击一个“翻转”按钮来翻转图像和我刚绘制的线条。代码为here on jsfiddle。
我目前的问题是:
任何帮助将不胜感激。
谢谢,
var context;
var canvas;
var imageObj = new Image();
var flipH = true;
var flipV = true;
var scaleH = 1,
scaleV = 1;
var posX = 0,
posY = 0;
var isDrawingFreeDraw;
canvas = document.getElementById('myCanvas');
context = canvas.getContext('2d');
context.strokeStyle = "#FFFF00";
//context.save();
canvas.addEventListener('mousedown', MouseDown, true);
canvas.addEventListener('mouseup', MouseUp, true);
canvas.addEventListener('mousemove', MouseMove, true);
imageObj.src = 'http://upload.wikimedia.org/wikipedia/commons/1/1a/Image_upload_test.jpg';
imageObj.onload = function () {
context.drawImage(imageObj, posX, posY, canvas.height * imageObj.width / imageObj.height, canvas.height);
};
console.log(context);
$(document).on('click', '#FlipH', function () {
console.log("Flip Me");
// context.restore();
context.save();
//canvas.width = 100;
scaleH = flipH ? -1 : 1;
context.scale(scaleH, scaleV);
posX = flipH ? (canvas.height * imageObj.width / imageObj.height) * -1 : 0;
context.drawImage(imageObj, posX, posY, canvas.height * imageObj.width / imageObj.height, canvas.height);
flipH = !flipH;
context.scale(1, 1);
//console.log(context);
context.restore();
});
function MouseUp(e) {
isDrawingFreeDraw = false;
context.save();
}
function MouseDown(e) {
context.save();
isDrawingFreeDraw = true;
console.log(e);
context.moveTo(e.pageX, e.pageY);
context.restore();
}
function MouseMove(e) {
if (isDrawingFreeDraw) {
context.save();
context.lineTo(e.pageX, e.pageY);
context.stroke();
context.restore();
}
}
答案 0 :(得分:1)
要翻转图像和图形,可以使用画布本身作为drawImage的源。
// draw the canvas to itself
ctx.drawImage(canvas,0,0);
演示:http://jsfiddle.net/m1erickson/Y9SLQ/
示例代码:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var img=new Image();
img.onload=start;
img.src="http://upload.wikimedia.org/wikipedia/commons/1/1a/Image_upload_test.jpg";
function start(){
canvas.width=img.width;
canvas.height=img.height;
ctx.drawImage(img,0,0);
ctx.beginPath();
ctx.moveTo(50,50);
ctx.lineTo(50,300);
ctx.lineTo(250,300);
ctx.lineWidth=8;
ctx.stroke();
}
$("#flipbutton").click(function(){
ctx.save();
ctx.translate(canvas.width,0);
ctx.scale(-1,1);
ctx.drawImage(canvas,0,0);
ctx.restore();
});