画布与图像旋转

时间:2017-05-26 06:11:09

标签: javascript jquery canvas

现在我要旋转图片。如果pic没有改变。我的代码是对的。但如果我改变我的Pic,我的画布将会消失。第一个代码是pic不能改变。最后一个是要改变的图片。



function rotateImg(direction) {
		var min_step = 0;
		var max_step = 3;
         var step = $(currentSource).attr("step");
        var id = $(".active")[0].id;
		if (step == null) {
			step = min_step;
		}
		if (direction == 'right') {
			step++;
            step > max_step && (step = min_step);
		} else {
			step--;
			step < min_step && (step = max_step);
		}
		$(currentSource).attr("step", step);
		var canvas = $("#canvas"+id)[0];
		var width = canvas.width;
		var height = canvas.height;
		var src = canvas.toDataURL("image/png");
		var img = new Image();
		var degree = step * 90 * Math.PI / 180;
		var ctx = canvas.getContext('2d');
		switch (step) {
			case 0:
				canvas.width = height;
				canvas.height = width;
				ctx.drawImage(currentSource, 0, 0,height,width);
				break;
			case 1:
				canvas.width = height;
				canvas.height = width;
				ctx.rotate(degree);
				ctx.drawImage(currentSource, 0, -height,width,height);
				break;
			case 2:
				canvas.width = height;
				canvas.height = width;
				ctx.rotate(degree);
				ctx.drawImage(currentSource, -height,-width ,height,width);
				break;
			case 3:
				canvas.width = height;
				canvas.height = width;
				ctx.rotate(degree);
				ctx.drawImage(currentSource, -width, 0,width,height);
				break;
		}
	}
&#13;
&#13;
&#13;

&#13;
&#13;
function rotateImg(direction) {
		var min_step = 0;
		var max_step = 3;
         var step = $(currentSource).attr("step");
        var id = $(".active")[0].id;
		if (step == null) {
			step = min_step;
		}
		if (direction == 'right') {
			step++;
            step > max_step && (step = min_step);
		} else {
			step--;
			step < min_step && (step = max_step);
		}
		$(currentSource).attr("step", step);
		var canvas = $("#canvas"+id)[0];
		var width = canvas.width;
		var height = canvas.height;
		var src = canvas.toDataURL("image/png");
		var imgs;
		var img = new Image();
		img.src = src;
		img.setAttribute("step",step);
		imgs = img;
		var degree = step * 90 * Math.PI / 180;
		var ctx = canvas.getContext('2d');
		switch (step) {
			case 0:
				canvas.width = height;
				canvas.height = width;
				ctx.drawImage(imgs, 0, 0,height,width);
				break;
			case 1:
				canvas.width = height;
				canvas.height = width;
				ctx.rotate(degree);
				ctx.drawImage(imgs, 0, -height,width,height);
				break;
			case 2:
				canvas.width = height;
				canvas.height = width;
				ctx.rotate(degree);
				ctx.drawImage(imgs, -height,-width ,height,width);
				break;
			case 3:
				canvas.width = height;
				canvas.height = width;
				ctx.rotate(degree);
				ctx.drawImage(imgs, -width, 0,width,height);
				break;
		}
	}
&#13;
&#13;
&#13;

0 个答案:

没有答案