jQuery('#carregar').click(function(){
var canvas = document.getElementById('canvas');
var image = document.getElementById('image');
var element = canvas.getContext("2d");
element.clearRect(0,canvas.width,canvas.height);
element.drawImage(image,300,300);
});
jsfiddle.net/braziel/nWyDE/
我有一个问题,将图像向右或向左旋转90°。
我在画布上使用一个图像,同一个屏幕将有几个画布等于示例,但我把它尽可能接近项目。
我问,当我点击“向左旋转”和“向右旋转”时,如何将图像向左或向右旋转90°?
我试过几个代码在互联网上,但没有工作。
解决方法
你可以使用canvas’context.translate& context.rotate来旋转你的图像
这里有一个函数来绘制旋转了指定度数的图像:
function drawRotated(degrees){
context.clearRect(0,canvas.height);
// save the unrotated context of the canvas so we can restore it later
// the alternative is to untranslate & unrotate after drawing
context.save();
// move to the center of the canvas
context.translate(canvas.width/2,canvas.height/2);
// rotate the canvas to the specified degrees
context.rotate(degrees*Math.PI/180);
// draw the image
// since the context is rotated,the image will be rotated also
context.drawImage(image,-image.width/2,-image.width/2);
// we’re done with the rotating so restore the unrotated context
context.restore();
}
这里是代码和小提琴:http://jsfiddle.net/m1erickson/6ZsCz/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var angleIndegrees=0;
var image=document.createElement("img");
image.onload=function(){
ctx.drawImage(image,canvas.width/2-image.width/2,canvas.height/2-image.width/2);
}
image.src="houseicon.png";
$("#clockwise").click(function(){
angleIndegrees+=30;
drawRotated(angleIndegrees);
});
$("#counterclockwise").click(function(){
angleIndegrees-=30;
drawRotated(angleIndegrees);
});
function drawRotated(degrees){
ctx.clearRect(0,canvas.height);
ctx.save();
ctx.translate(canvas.width/2,canvas.height/2);
ctx.rotate(degrees*Math.PI/180);
ctx.drawImage(image,-image.width/2);
ctx.restore();
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas><br>
<button id="clockwise">Rotate right</button>
<button id="counterclockwise">Rotate left</button>
</body>
</html>