HTML5 Canvas图片操作简单实例1
1.加载显示图片
<canvas id="canvasOne" class="myCanvas" width="500" height="500"></canvas> <script> var canvas = document.getElementById('canvasOne'); var ctx = canvas.getContext('2d'); //加载图片 var img = new Image(); img.onload = function () { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(img, 0, 0, img.width, img.height); } img.src = '../images/1.jpg'; </script>
2.获取Canvas数据,显示到img标签
<canvas id="canvasOne" class="myCanvas" width="500" height="500"></canvas> <img id="imgOne" /> <script> var canvas = document.getElementById('canvasOne'); var ctx = canvas.getContext('2d'); //加载图片,显示当前图片到其他地方 var img = new Image(); img.onload = function () { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(img, 0, 0, img.width, img.height); //显示图片的部分内容到img图片标签 var imgOne = document.getElementById('imgOne'); imgOne.width = 1000; imgOne.height = 600; //图片内容显示当前画布显示的部分 imgOne.src = canvas.toDataURL('image/png'); } img.src = '../images/1.jpg'; </script>
3.获取Canvas数据,显示到其他canvas中
<canvas id="target" width="200" height="100"></canvas> <canvas id="canvasOne" class="myCanvas" width="500" height="500"></canvas> <script> var canvas = document.getElementById('canvasOne'); var ctx = canvas.getContext('2d'); var target = document.getElementById('target'); //加载图片 var img = new Image(); img.onload = function () { ctx.clearRect(0, 0, canvas.width, canvas.height); //图片缩小,显示 ctx.scale(0.5, 0.5); ctx.drawImage(img, 0, 0, img.width, img.height); //获取缩小后的像素,显示到其他canvas var imgData = ctx.getImageData(0, 0, 200, 100); var ctxTwo = target.getContext('2d'); ctxTwo.putImageData(imgData, 0, 0); } img.src = '../images/1.jpg'; </script>
4.Canvas中图片的平铺操作
<canvas id="canvasOne" class="myCanvas" width="500" height="500"></canvas> <script> /***图片的背景显示***/ var canvas = document.getElementById('canvasOne'); var ctx = canvas.getContext('2d'); //加载图片 var img = new Image(); img.onload = function () { ctx.beginPath(); ctx.rect(0, 0, canvas.width, canvas.height); ctx.scale(0.1, 0.1); //平铺 //ctx.fillStyle = ctx.createPattern(img, 'repeat'); //水平方向 平铺 //ctx.fillStyle = ctx.createPattern(img,'repeat-x'); //垂直方向 平铺 //ctx.fillStyle = ctx.createPattern(img, 'repeat-y'); //禁用平铺 ctx.fillStyle = ctx.createPattern(img, 'no-repeat'); ctx.fill(); } img.src = '../images/1.jpg'; </script>
更多像素处理: