canvas-实例

基本

    window.onload = function(){
        var drawing = document.getElementById("drawing");
        //make sure <canvas> is completely supported
        if (drawing.getContext){
            var context = drawing.getContext("2d");
            // 红色矩形
            context.fillStyle = "#ff0000";
            context.fillRect(10, 10, 50, 50);
            // 半透明的蓝色矩形
            context.fillStyle = "rgba(0,0,255,0.5)";
            context.fillRect(30, 30, 50, 50);
            // 清除两个矩形重叠的矩形
            context.clearRect(40, 40, 10, 10);
        } else {
            document.write("未找到 Canvas 对象");
        }
    };

把canvas的数据转换为图片

var imgURI = drawing.toDataURL();
// 插入 img dom 对象
var image = document.createElement("img");
image.src = imgURI;
document.body.appendChild(image);

把 img 图片画入 canvas

                var context = drawing.getContext("2d");
                var image = document.getElementById("smiley");
                // draw regular size
                context.drawImage(image, 10, 10);
                // draw smaller
                context.drawImage(image, 50, 10, 20, 30);
                // draw just part of the image
                context.drawImage(image, 0, 10, 50, 50, 0, 100, 40, 60);

渐变的矩形

                var context = drawing.getContext("2d"),
                    gradient = context.createLinearGradient(30, 30, 70, 70);
                gradient.addColorStop(0, "white");
                gradient.addColorStop(1, "black");
                //draw a red rectangle
                context.fillStyle = "#ff0000";
                context.fillRect(10, 10, 50, 50);
                //draw a gradient rectangle
                context.fillStyle = gradient;
                context.fillRect(30, 30, 50, 50);

图片的 repeat

                var context = drawing.getContext("2d"),
                    image = document.images[0],
                    pattern = context.createPattern(image, "repeat");
                context.fillStyle = pattern;
                context.fillRect(10, 10, 150, 150);

阴影

    var context = drawing.getContext("2d");
    // 阴影设置
    context.shadowOffsetX = 5;
    context.shadowOffsetY = 5;
    context.shadowBlur    = 4;
    context.shadowColor   = "rgba(0, 0, 0, 0.5)";
    context.fillStyle = "#ff0000";
    context.fillRect(10, 10, 50, 50);
    context.fillStyle = "rgba(0,0,255,1)";
    context.fillRect(30, 30, 50, 50);

全局透明度与rgba

var context = drawing.getContext("2d");
context.fillStyle = "#ff0000";
context.fillRect(10, 10, 50, 50);
context.globalAlpha = 0.1;
context.fillStyle = "rgba(0,0,255,1)";
context.fillRect(30, 30, 50, 50);

写入文本

if (context.strokeText){
    context.font = "bold 14px Arial";
    context.textAlign = "center"; // start | center | end
    context.textBaseline = "middle";
    context.fillText("12", 100, 20);
} else {
    alert("Your browser doesn't support the canvas text API.");
}