码迷,mamicode.com
首页 > 其他好文 > 详细

练习图像

时间:2017-11-02 01:02:48      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:font   function   draw   height   tco   scale   图像   order   block   

<canvas id="canvas" width="500" height="500" style="border:1px solid #666;display:block;margin:0 auto">
    当前浏览器不支持canvas,请更换浏览器后再试。
</canvas>
<input type="range" id="scale-range" min="0.5" max="3.0" step="0.1" value="1.0" style="display: block;width:500px;margin:0 auto;margin-top:20px;">
<canvas id="watermask-canvas" style="display:none;border:1px solid #666;margin:0 auto">当前浏览器不支持canvas,请更换浏览器后再试。</canvas>
var canvas = document.getElementById(‘canvas‘);
var context = canvas.getContext(‘2d‘);
var slider = document.getElementById(‘scale-range‘);
var img = new Image();
var sw = canvas.width;//设置canvas中图像宽度
var sy = canvas.height;//设置canvas中图像高度

var watermaskCanvas = document.getElementById(‘watermask-canvas‘);
var watermaskContext = watermaskCanvas.getContext(‘2d‘);
window.onload = function(){

    img.src = ‘fanfan.jpg‘;

    var scale = slider.value;
    img.onload = function(){//必须等img onload完之后才可以绘制img
        drawImageByScale(scale);
        slider.onmousemove = function(){
            scale = slider.value;
            drawImageByScale(scale);
        }
    }

    // 设置 watermask canvas
    watermaskCanvas.width = 150;
    watermaskCanvas.height = 60;

    watermaskContext.font = ‘bold 30px 宋体‘;
    watermaskContext.fillStyle = ‘rgba(0, 0, 0, 0.5)‘;
    watermaskContext.textAlign = ‘center‘
    watermaskContext.textBaseline = ‘middle‘;
    watermaskContext.fillText(‘水印 - 水印‘, 75, 25);
}

function drawImageByScale(scale){
    var imgWidth = sw * scale;//缩放后的图像宽
    var imgHeight = sy * scale;//缩放后的图像高
    var dx = (canvas.width - imgWidth) / 2;//缩放后的图像在x轴上的偏移量
    var dy = (canvas.height - imgHeight) / 2;//缩放后的图像在y轴上的偏移量
    context.clearRect(0, 0, canvas.width, canvas.height);//重新绘制缩放后的图像前,需要清空之前绘制的图像。
    context.drawImage(img, dx, dy, imgWidth, imgHeight);
    context.drawImage(watermaskCanvas, canvas.width - watermaskCanvas.width, canvas.height - watermaskCanvas.height);
}

 

练习图像

标签:font   function   draw   height   tco   scale   图像   order   block   

原文地址:http://www.cnblogs.com/cornlin/p/7769180.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!