Canvas

svg

canvas属性

基于canvas实现物理运动效果与动画效果

Canvas需要在标签里加属性 设置宽高 
Canvas默认的宽高 300*150 
WebGL可以实现3D效果 Canvas 本身不支持3D效果 

绘制路径

<canvas id="myCavas" width="800" height="600" style="border:1px solid  black">您的浏览器版本太低,赶紧换一个吧</canvas>
<script type="text/javascript">
	//获取元素
	var c = document.getElementById("myCavas");
	//获取绘图元素对象
	var ctx = c.getContext("2d");
	//1.设置起始位置  X轴  Y 轴
	ctx.moveTo(100, 100);
	//2.设置结束位置
	ctx.lineTo(200, 100);
	//3.加线条颜色
	ctx.strokeStyle = "red";
	//4.渲染
	ctx.stroke();

	//开辟新的绘制路径,否则后面的颜色会覆盖
	ctx.beginPath();
	ctx.moveTo(100, 200);
	ctx.lineTo(200, 200);
	ctx.lineTo(200, 300);
	ctx.strokeStyle = "blue";
	ctx.closePath(); //闭合路径
	ctx.stroke();

	ctx.beginPath();
	ctx.moveTo(100, 200);
	ctx.lineTo(100, 300);
	ctx.lineTo(200, 300);
	ctx.closePath();
	ctx.strokeStyle = "red";
	ctx.stroke();

	//填充绘制
	ctx.beginPath();
	ctx.moveTo(100, 400);
	ctx.lineTo(200, 400);
	ctx.lineTo(200, 500);
	ctx.fillStyle = "red"
	ctx.closePath();
	ctx.fill();

	//矩形擦除 X轴 Y轴  Width 宽  Height 高
	//清空指定位置的 矩形区域
	//ctx.clearRect(100, 200, 50, 50);
	//清除整个画布
	//ctx.clearRect(0, 0, c.width, c.height);

	ctx.beginPath();
	ctx.lineWidth = "100"; //设置线的宽度
	ctx.strokeStyle = "lightblue"
	//端点样式 :
	//butt默认 
	//round圆角  
	//square平角(设置后,两端边长宽度的一半)
	ctx.lineCap = "round";
	ctx.moveTo(300, 200);
	ctx.lineTo(400, 300);
	ctx.stroke();

</script>

绘制矩形

<canvas id="myCanvas" width="800" height="600" style="border: 1px solid black;"></canvas>
<script type="text/javascript">
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.strokeStyle = "blue";
ctx.lineWidth = "10";
//连接线连接点样式
//miter 默认 round 圆角 bevel 斜角
ctx.lineJoin = "round";
//下面  自动完成beginPath() 
ctx.strokeRect(10, 10, 50, 100);

ctx.fillStyle = "red";
ctx.fillRect(200, 10, 100, 200);
</script>

 画板

<style type="text/css">
#myButton {
    display: inline-block;
    width: 200px;
    height: 100px;
    background: green;
    font-size: 50px;
}

#myCanvas {
    cursor: crosshair;
}
</style>
</head>

<body>
<canvas id="myCanvas" width="800" height="500" style="border: 1px solid black;"></canvas>
<button id="myButton" onclick="reset()">重置</button>
<script type="text/javascript">
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
//绑定鼠标点击事件
c.onmousedown = function(e) {
    var e = e || window.event;
    ctx.beginPath();
    ctx.moveTo(e.clientX - c.offsetLeft, e.clientY - c.offsetTop);
    ctx.strokeStyle = randColor();
    c.onmousemove = function(e) {
        var e = e || window.event;
        ctx.lineTo(e.clientX - c.offsetLeft, e.clientY - c.offsetTop);

        ctx.lineWidth = "10";
        ctx.lineCap = "round";
        ctx.stroke();
    }
}

c.onmouseup = function() {
    c.onmousemove = null;
}

function reset() {
    window.location.reload();
}

function randColor() {
    var r = Math.floor(Math.random() * (255 - 0 + 1) + 0);
    var g = Math.floor(Math.random() * (255 - 0 + 1) + 0);
    var b = Math.floor(Math.random() * (255 - 0 + 1) + 0);
    return "rgb(" + r + "," + g + "," + b + ")";
}
</script>

 钟表 

<canvas id="canvas" width="800" height="800" style="border: 1px solid black;"></canvas>
<script>

var theCan = document.getElementById("canvas");
var ctx = theCan.getContext("2d");

function toDraw(){
    // 圆心位置
    var x = 200;
    var y = 200;
    var r = 150;
    // 清除画布内容
    ctx.clearRect(0,0,theCan.width,theCan.height);
    // 获取当前时间
    var ODate = new Date();
    var oHours = ODate.getHours();
    var oMin = ODate.getMinutes();
    var oSen = ODate.getSeconds();

    // 计算角度值 oMin / 2: 一分钟走 多少度
    var hoursValue = (-90 + oHours * 30 + oMin / 2) * Math.PI/180;
    var minValue = (-90 + oMin * 6) * Math.PI/180;
    var senValue = (-90 + oSen * 6) * Math.PI/180;

    // 绘制刻度
    ctx.beginPath();
    for(var i = 0; i < 60; i++){
        ctx.moveTo(x,y);
        ctx.arc(x,y,r,i * 6 * Math.PI / 180, (i + 1) * 6 * Math.PI / 180,false);
    }
    ctx.closePath();
    ctx.stroke();

    //覆盖白色圆
    ctx.beginPath();
    ctx.fillStyle = "#FFFFFF";
    ctx.moveTo(x,y);
    ctx.arc(x,y,r - 5, 0, 2 * Math.PI, false);
    ctx.closePath();
    ctx.fill();

    //绘制刻度12
    ctx.beginPath();
    ctx.lineWidth = 5;
    for(var i = 0; i < 12; i++){
        ctx.moveTo(x,y);
        ctx.arc(x,y,r,i * 30 * Math.PI / 180, (i + 1) * 30 * Math.PI / 180,false);
    }
    ctx.closePath();
    ctx.stroke();

    //覆盖白色圆
    ctx.beginPath();
    ctx.fillStyle = "#FFFFFF";
    ctx.moveTo(x,y);
    ctx.arc(x,y,r - 10, 0, 2 * Math.PI, false);
    ctx.closePath();
    ctx.fill();

    // 画时针
    ctx.lineWidth = 5;
    ctx.beginPath();
    ctx.moveTo(x,y);
    ctx.arc(x,y,r - 75, hoursValue,hoursValue,false);
    ctx.closePath();
    ctx.stroke();
    // 分针
    ctx.lineWidth = 3;
    ctx.beginPath();
    ctx.moveTo(x,y);
    ctx.arc(x,y,r - 60, minValue,minValue,false);
    ctx.closePath();
    ctx.stroke();
    // 秒针
    ctx.lineWidth = 1;
    ctx.beginPath();
    ctx.moveTo(x,y);
    ctx.arc(x,y,r - 30, senValue,senValue,false);
    ctx.closePath();
    ctx.stroke();

}
setInterval(function(){
    toDraw();
},1000);
</script>

 圆弧

<canvas id="myCanvas" width="800" height="500" style="border: 1px solid black;"></canvas>
<script type="text/javascript">
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(200, 200);   
//起点 可以形成扇形
//X坐标  Y坐标 :圆心  半径 起始角度  结束角度  是否顺时针 false :顺时针
//弧度 = 角度 * PI /180
ctx.arc(200, 200, 100, 0, 90 * Math.PI / 180, false);
ctx.fill();

//饼状图
//设置数据
var data = [{
        value: 0.3,
        color: "red"
    }, {
        value: 0.1,
        color: "blue"
    }, {
        value: 0.2,
        color: "green"
    }, {
        value: 0.4,
        color: "pink"
    }, ]
    //圆心
var beginX = 300;
var beginY = 300;
//半径
var radius = 100;
//起始角度
var tempAngle = -90;
for(var i = 0; i < data.length; i++) {
    var angle = data[i].value * 360;
    //起始弧度
    var beginAngle = tempAngle * Math.PI / 180;
    var endAngle = (tempAngle + angle) * Math.PI / 180;

    ctx.beginPath();
    ctx.moveTo(beginX, beginY);
    ctx.fillStyle = randColor();
    //ctx.fillStyle = data[i].color;
    ctx.arc(beginX, beginY, radius, beginAngle, endAngle, false);
    ctx.closePath();
    ctx.fill();
    tempAngle += angle;
}

function randColor() {
    var r = Math.floor(Math.random() * (255 - 0 + 1) + 0);
    var g = Math.floor(Math.random() * (255 - 0 + 1) + 0);
    var b = Math.floor(Math.random() * (255 - 0 + 1) + 0);
    return "rgb(" + r + "," + g + "," + b + ")";
}
</script>

贝塞尔曲线

二次贝塞尔曲线
ctx.beginPath();
ctx.moveTo(100, 100);
(控制点坐标  结束点坐标)
ctx.quadraticCurveTo(100, 300, 300, 100);
ctx.stroke();

三次贝塞尔曲线
ctx.beginPath();
ctx.moveTo(100, 100);
//三次贝塞尔曲线
(控制点坐标  控制点坐标 结束点坐标)
ctx.bezierCurveTo
(100, 300, 300, 300, 300, 100);
ctx.stroke();

八卦

<canvas id="canvas" width="800" height="600" style="border: 1px solid black;"></canvas>
<script>
    var oCanvas = document.getElementById("canvas");
    var ctx = oCanvas.getContext("2d");
    ctx.translate(400, 300);

    function toDraw() {
        ctx.clearRect(0,0,800,600);
        ctx.rotate(Math.PI/180);

        //最大圆
        ctx.beginPath();
        ctx.arc(0, 0, 200, 0, 2 * Math.PI, false);
        ctx.fill();

        //白的半圆
        ctx.beginPath();
        ctx.fillStyle = "white";
        ctx.arc(0, 0, 200, 0.5 * Math.PI, 1.5 * Math.PI, false);
        ctx.fill();

        //小圆黑的
        ctx.beginPath();
        ctx.fillStyle = "black";
        ctx.arc(0, -100, 100, 0, 2 * Math.PI, false);
        ctx.fill();

        //小圆白的
        ctx.beginPath();
        ctx.fillStyle = "white";
        ctx.arc(0, 100, 100, 0, 2 * Math.PI, false);
        ctx.fill();

        //小圆点白
        ctx.beginPath();
        ctx.fillStyle = "white";
        ctx.arc(0, -100, 25, 0, 2 * Math.PI, false);
        ctx.fill();

        //小圆点黑
        ctx.beginPath();
        ctx.fillStyle = "black";
        ctx.arc(0, 100, 25, 0, 2 * Math.PI, false);
        ctx.fill();
        window.requestAnimationFrame(toDraw);
    }
    window.requestAnimationFrame(toDraw);
</script>

线性渐变

ctx.beginPath();
ctx.moveTo(100, 100);
ctx.lineTo(300, 100);
ctx.lineWidth = 20;
//创建线性渐变 起始位置(X, Y)  结束位置(X, Y) 
var oClg = 
ctx.createLinearGradient(100, 100, 300, 100);
//添加渐变点
//渐变点为0至1之间的小数
oClg.addColorStop(0, "red");
oClg.addColorStop(0.5, "green");
oClg.addColorStop(1, "blue");
//将渐变对象付给线的样式
ctx.strokeStyle = oClg;
ctx.stroke();

径向渐变

//创建径向渐变 起始小圆位置(X, Y, R)  结束大圆位置(X, Y, R) 
var oClg = 
ctx.createRadialGradient(380, 250, 15, 300, 300, 200);
//添加渐变点
oClg.addColorStop(0, "white");
oClg.addColorStop(0.3, "yellow");
oClg.addColorStop(1, "black");
//将渐变对象付给线的样式
ctx.fillStyle = oClg;
ctx.arc(300, 300, 200, 0, 2 * Math.PI, false);
ctx.fill();

变换

//1.平移
ctx.save() //保存路径 :可以使画布单独形成一个独立的区域
ctx.translate(100, 100); //画布平移 X , Y
ctx.arc(100, 100, 100, 0, 2 * Math.PI, false);
ctx.fill();
ctx.restore(); //恢复路径

ctx.beginPath();
ctx.fillStyle = "red";
ctx.arc(100, 100, 100, 0, 2 * Math.PI, false);
ctx.fill();

//2.缩放
ctx.save();
ctx.scale(2, 2);
ctx.beginPath();
ctx.arc(100, 100, 100, 0, 2 * Math.PI, false);
ctx.fillStyle = "red";
ctx.fill();
ctx.restore();

//3.rotate 旋转
//平移画布到中心点,旋转,画布平移回去
ctx.save();
ctx.translate(400, 350);//重心
ctx.rotate(90 * Math.PI / 180); 
ctx.translate(-400, -350);
ctx.fillRect(300, 300, 200, 100);
ctx.restore();

让矩形围绕着重心旋转动画(一)
var angle = 0;
setInterval(function() {
    ctx.
    clearRect(0, 0, oCanvas.width, oCanvas.height);
    angle++;
    ctx.save();
    ctx.translate(300, 300);//画布平移至重心点
    ctx.rotate(angle * Math.PI / 180); 
    ctx.fillRect(-100, -50, 200, 100);
    ctx.restore();
}, 20);

让矩形围绕着重心旋转动画(二)
var angle = 0;
function toDraw() {
    ctx.
    clearRect(0, 0, oCanvas.width, oCanvas.height);
    angle++;
    ctx.save();
    ctx.translate(300, 300);
    ctx.fillStyle = randColor();
    ctx.rotate(angle * 100 * Math.PI / 180); 
    ctx.fillRect(-100, -50, 200, 100);
    ctx.restore();
    window.requestAnimationFrame(toDraw);
};
window.requestAnimationFrame(toDraw);
//requestAnimationFrame性能比setinterval高

function randColor() {
    var r = Math.floor(Math.random() * (255 - 0 + 1) + 0);
    var g = Math.floor(Math.random() * (255 - 0 + 1) + 0);
    var b = Math.floor(Math.random() * (255 - 0 + 1) + 0);
    return "rgb(" + r + "," + g + "," + b + ")";
}

绘制图片

var img = new Image();
img.src = "01.jpg";
img.onload = function(){
    ctx.drawImage(img, 0, 0);//图片对象, 位置
    ctx.drawImage(img, 0, 0, 300, 200);//图片对象, 位置, 大小
    //绘制图片(图片对象, 截取起始位置, 图片截取的范围 宽度 高度, 放置在画布上的位置 X Y,图片的宽度 高度 )
    ctx.drawImage(img, 0, 0, 200, 200, 20, 20, 200, 200);
    // 如果图片的宽高与截取的宽高一致, 以原来的尺寸进行截取
}

像素操作

//创建图片对象
var img = new Image();
img.src = "01.jpg";
img.onload = function() {
    ctx.drawImage(img, 0, 0, 800, 600);
    // 获取像素对象
    var imgDate = ctx.getImageData(0, 0, oCanvas.width, oCanvas.height);
    console.log(imgDate);
    // 反色:补色
    // 是与原色叠加变为白色的颜色
    // 素组中每隔四个元素是一个像素点信息
    for(var i = 0; i < imgDate.data.length; i += 4) {
        imgDate.data[i] = 255 - imgDate.data[i];
        imgDate.data[i + 1] = 255 - imgDate.data[i + 1];
        imgDate.data[i + 2] = 255 - imgDate.data[i + 2];
    }
    //黑白
    for(var i = 0; i < imgDate.data.length; i+=4){
        var gray = Math.floor((imgDate.data[i] + imgDate.data[i + 1] + imgDate.data[i + 2]) / 3);
        imgDate.data[i] = gray;
        imgDate.data[i + 1] = gray;
        imgDate.data[i + 2] = gray;
    }
    ctx.putImageData(imgDate, 400, 0);

图形结合方式

<a href="http://www.w3school.com.cn/tags/canvas_globalcompositeoperation.asp">globalCompositeOperation
</a>
<canvas id="myCanvas" width="800" height="600" style="border: 1px solid black;">
</canvas>

<script type="text/javascript">
    var oCanvas = document.getElementById("myCanvas");
    var ctx = oCanvas.getContext("2d");

    ctx.beginPath();
    ctx.fillStyle = "blue"; //目标图像
    ctx.fillRect(200, 200, 200, 200);
    ctx.fill();
    ctx.globalCompositeOperation = "xor";

    ctx.beginPath();
    ctx.fillStyle = "red"; //源图像
    ctx.fillRect(150, 200, 100, 100);
    ctx.fill();
</script>

source-over 
默认。在目标图像上显示源图像。
source-atop 
在目标图像顶部显示源图像。
源图像位于目标图像之外的部分是不可见的。
source-in   
在目标图像中显示源图像。
只有目标图像内的源图像部分会显示,目标图像是透明的。
source-out  
在目标图像之外显示源图像。
只会显示目标图像之外源图像部分,目标图像是透明的。

destination-over      
在源图像上方显示目标图像。
destination-atop      
在源图像顶部显示目标图像。
源图像之外的目标图像部分不会被显示。
destination-in    
在源图像中显示目标图像。
只有源图像内的目标图像部分会被显示,源图像是透明的。
destination-out   
在源图像外显示目标图像。
只有源图像外的目标图像部分会被显示,源图像是透明的。

lighter 显示源图像 + 目标图像。
copy     显示源图像。忽略目标图像。
xor 使用异或操作对源图像与目标图像进行组合。

运动方块

<canvas id="myCanvas" width="800" height="600" style="border: 1px solid black;"></canvas>
<script type="text/javascript">
var oCanvas = document.getElementById("myCanvas");
var ctx = oCanvas.getContext("2d");

function React(x, y, w, h, color) {
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.color = color;
}
//创建矩形对象
var rt1 = new React(0, 0, 50, 50, "red");
var speed = 10;
function toDraw() {
    ctx.clearRect(0, 0, oCanvas.width, oCanvas.height);
    rt1.x += speed;
    ctx.fillStyle = rt1.color;
    ctx.fillRect(rt1.x, rt1.y, rt1.w, rt1.h);
    if(rt1.x + rt1.w >= oCanvas.width || rt1.x < 0) {
        speed = -speed;
    }
    window.requestAnimationFrame(toDraw);
}
window.requestAnimationFrame(toDraw);
</script>

许多运动小球

<style type="text/css">
    html,
    body {
        margin: 0;
        padding: 0;
        height: 100%;
        width: 100%;
    }
</style>
</head>

<body>
<canvas id="myCanvas"></canvas>
<script type="text/javascript">
    var oCanvas = document.getElementById("myCanvas");
    var ctx = oCanvas.getContext("2d");
    oCanvas.width = document.body.clientWidth;
    oCanvas.height = document.body.clientHeight;
    //圆的构造函数
    function Circle(x, y, r, speedx, speedy, color) {
        this.x = x;
        this.y = y;
        this.r = r;
        this.speedx = speedx;
        this.speedy = speedy;
        this.color = color;
    }

    //随机函数
    function random(min, max) {
        return Math.floor(Math.random() * (max - min + 1) + min);
    }

    //小球的数量

    var aryc = [];
    var num = 100;
    for(var i = 0; i < num; i++) {
        var r = random(5, 100);

        var x = random(0 + 2 * r, oCanvas.width - 2 * r);
        var y = random(0 + 2 * r, oCanvas.height - 2 * r);

        var speedx = random(5, 10);
        var speedy = random(5, 10);
        var color = "rgba(" + random(0, 255) + "," + random(0, 255) + "," + random(0, 255) + "," + random(1, 10) / 10 + ")";
        aryc.push(new Circle(x, y, r, speedx, speedy, color));
    }

    function drawCircle(obj) {
        ctx.beginPath();
        ctx.fillStyle = obj.color;
        ctx.arc(obj.x, obj.y, obj.r, 0, 2 * Math.PI, false);
        ctx.fill();

    }

    function toDraw() {
        ctx.clearRect(0, 0, oCanvas.width, oCanvas.height);
        for(var i = 0; i < aryc.length; i++) {
            aryc[i].x += aryc[i].speedx;
            aryc[i].y += aryc[i].speedy;

            //碰壁判断
            if((aryc[i].x + aryc[i].r * 2) >= oCanvas.width || (aryc[i].x - aryc[i].r) <= 0) {
                aryc[i].speedx = -aryc[i].speedx;
            }

            if((aryc[i].y + aryc[i].r * 2) >= oCanvas.height || (aryc[i].y - aryc[i].r) <= 0) {
                aryc[i].speedy = -aryc[i].speedy;
            }
            drawCircle(aryc[i]);
        }
        window.requestAnimationFrame(toDraw);
    }
    window.requestAnimationFrame(toDraw);
</script>

刮刮卡

<style type="text/css">
    html,
    body {
        margin: 0;
        padding: 0;
    }
    #myDiv {
        width: 300px;
        height: 100px;
        background: red;
        position: relative;
        font-size: 40px;
        text-align: center;
        line-height: 100px;
        color: white;
    }
    #myCanvas {
        position: absolute;
        left: 0;
        top: 0;
    }
</style>
</head>
<body>
<div id="myDiv"> 谢谢惠顾 <canvas id="myCanvas" width="300" height="100"></canvas> </div>
<script type="text/javascript">
    var oCanvas = document.getElementById("myCanvas");
    var ctx = oCanvas.getContext("2d")
    //绘制灰色
    ctx.beginPath();
    ctx.fillStyle = "gray";
    ctx.fillRect(0, 0, oCanvas.width, oCanvas.height);
    ctx.fill();
    //设置组合效果
    ctx.globalCompositeOperation = "destination-out";
    //绑定鼠标按键
    oCanvas.onmousedown = function(e) {
        e = e || window.event;
        ctx.beginPath();
        ctx.fillStyle = "green";
        ctx.arc(e.clientX, e.clientY, 30, 0, 2 * Math.PI, false);
        ctx.fill();
        oCanvas.onmousemove = function(e) {
            e = e || window.event;
            ctx.beginPath();
            ctx.fillStyle = "green";
            ctx.arc(e.clientX, e.clientY, 30, 0, 2 * Math.PI, false);
            ctx.fill();
        };
        oCanvas.onmouseup = function() {
            oCanvas.onmousemove = null;
            //获取像素对象
            var imgData = ctx.getImageData(0, 0, oCanvas.width, oCanvas.height);
            //计算透明像素点的数量
            var opacity = 0;
            for(var i = 0; i < imgData.data.length; i += 4) {
                if(imgData.data[i + 3] == 0) {
                    opacity++;
                }
            }
            if(opacity / (imgData.data.length / 4) >= 0.5) {
                alert("谢谢惠顾");
            }
        }

    }
</script>
</body>

朋友圈签名Canvas画图

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            @font-face {
                font-family: "白舟極太楷書教漢";
                src: url("font/白舟極太楷書教漢.ttf");
            }

            .p_1{
                font-family: "白舟極太楷書教漢";
            }
        </style>
    </head>

    <body>
        <div class="enter">
            <p class="p_1">撒打发斯蒂芬</p>
            <input type="text" class="enter_name" />
            <input type="button" value="确定" onclick="generate()" />
        </div>
        <div class="canvas_1">
            <canvas id="myCanvas_1" width="400" height="100"></canvas>
        </div>
        <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
        <script type="text/javascript">
            var enter_name;

            var img = new Image();
            img.src = "img/001.png";
            img.onload = function() {
                //ctx.drawImage(img, 0, 0); //图片对象, 位置
                //ctx.drawImage(img, 0, 0, 300, 200); //图片对象, 位置, 大小
                //绘制图片(图片对象, 截取起始位置, 图片截取的范围 宽度 高度, 放置在画布上的位置 X Y,图片的宽度 高度 )
                //.drawImage(img, 0, 0, 200, 200, 20, 20, 200, 200);
                // 如果图片的宽高与截取的宽高一致, 以原来的尺寸进行截取
            }

            function generate() {
                enter_name = $(".enter_name").val();
                if(enter_name == "") {
                    alert("请输入姓名");
                    return;
                }
                var ctx_1 = document.getElementById("myCanvas_1").getContext("2d");
                ctx_1.font = "30px 白舟極太楷書教漢";
                ctx_1.drawImage(img, 0, 0); //图片对象, 位置
                ctx_1.fillText(enter_name, 100, 40);
            }
        </script>
    </body>

</html>

动画部分

hover效果

<style type="text/css">
    html,body{
        margin: 0;
        padding: 0;
    }
    #myCanvas{
        border: 1px solid black;
    }
</style>
</head>
<body>
<canvas id="myCanvas" width="800" height="600"></canvas>
<script type="text/javascript">
    var oCanvas = document.getElementById("myCanvas");
    var ctx = oCanvas.getContext("2d");
    //绘制矩形
    function drawRect(obj){
        ctx.beginPath();
        ctx.fillStyle = obj.fillstyle;
        ctx.rect(obj.x, obj.y, obj.w, obj.h);
        ctx.fill();
    }
    //矩形的构造函数
    function Rect(x, y, w, h, fillstyle){
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
        this.fillstyle = fillstyle;
        drawRect(this);
    }
    var rt1 = new Rect(100, 100, 100, 100, "blue");
    oCanvas.onmousemove = function(e){
        var e = e || window.event;
        //清除
        ctx.clearRect(0, 0, oCanvas.width, oCanvas.height);
        var mx = e.clientX;
        var my = e.clientY;

        //判断鼠标位置是否在矩形内
        //if(rt1.x <= mx && (rt1.x + rt1.w) >= mx && rt1.y <= my && (rt1.y + rt1.h) >= my){
        //  rt1.fillstyle = "red";
        //} else {
        //  rt1.fillstyle = "blue";
        //}
        //判定指定位置是否在当前绘图路径内部
        if(ctx.isPointInPath(mx, my)){
            rt1.fillstyle = "red";
        } else {
            rt1.fillstyle = "blue";
        }
        drawRect(rt1);
    }
</script>

多物体效果

<style type="text/css">
html,
    body {
        margin: 0;
        padding: 0;
    }

    #myCanvas {
        border: 1px solid black;
    }
</style>
</head>

<body>
<canvas id="myCanvas" width="800" height="800"></canvas>
<script type="text/javascript">
    var oCanvas = document.getElementById("myCanvas");
    var ctx = oCanvas.getContext("2d");
    //绘制矩形
    function drawRect(obj) {
        ctx.beginPath();
        ctx.fillStyle = obj.fillstyle;
        ctx.rect(obj.x, obj.y, obj.w, obj.h);
        //ctx.fill();
    }
    //矩形的构造函数
    function Rect(x, y, w, h, fillstyle) {
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
        this.fillstyle = fillstyle;
        drawRect(this);
    }
    var str = [];
    var num = 10;
    for(var i = 0; i < num; i++) {
        str[i] = new Rect(50 * i, 50 * i, 50, 50, "blue");
        ctx.fill();
    }
    oCanvas.onmousemove = function(e) {
        for(var i = 0; i < num; i++) {
            var e = e || window.event;
            var mx = e.clientX;
            var my = e.clientY;
            drawRect(str[i]);
            //判定指定位置是否在当前绘图路径内部
            if(ctx.isPointInPath(mx, my)) {
                str[i].fillstyle = "red";
            } else {
                str[i].fillstyle = "blue";
            }
            ctx.fill();
        }
    }
</script>
</body>

拖拽_1

<style type="text/css">
    html,
    body {
        margin: 0;
        padding: 0;
    }
</style>
</head>

<body>
<canvas id="myCanvas" width="800" height="800" style="border: 1px solid black;"></canvas>
<script type="text/javascript">
    var oCanvas = document.getElementById("myCanvas");
    var ctx = oCanvas.getContext("2d");
    //绘制矩形
    function drawRect(obj) {
        ctx.beginPath();
        ctx.fillStyle = obj.fillstyle;
        ctx.rect(obj.x, obj.y, obj.w, obj.h);
        ctx.fill();
    }
    //矩形的构造函数
    function Rect(x, y, w, h, fillstyle) {
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
        this.fillstyle = fillstyle;
        drawRect(this);
    }
    var str = [];
    var num = 10;
    for(var i = 0; i < num; i++) {
        str[i] = new Rect(50 * i, 50 * i, 50, 50, "blue");
    }
    oCanvas.onmousedown = function(e){
        var e = e || window.event;
        //声明一个空对象(储存哪一个要移动)
        var moveObj = null;
        //移动对象的位置
        var mox = 0;
        var moy = 0;
        //获取鼠标初始的位置
        var mx = e.clientX;
        var my = e.clientY;
        for(var i = 0; i < str.length; i++){
            if(mx >= str[i].x && mx <= str[i].x + str[i].w && my >= str[i].y && my <= str[i].y + str[i].h){
                moveObj = str[i];
                //获取移动对象的初始位置
                mox = str[i].x;
                moy = str[i].y;
            }
        }
        //判断是否存在移动对象
        if(moveObj){
            oCanvas.onmousemove = function(e){
                //清空画布
                ctx.clearRect(0, 0, oCanvas.width, oCanvas.height);
                var e = e || window.event;
                //获取当前鼠标的位置
                var mx2 = e.clientX;
                var my2 = e.clientY;
                //更新移动搞对象的位置
                moveObj.x = mox + (mx2 - mx);
                moveObj.y = moy + (my2 - my);
                for(var i = 0; i < str.length; i++){
                    drawRect(str[i]);
                }
            }
            oCanvas.onmouseup = function(){
                oCanvas.onmousemove = null;
            }
        }
    }
</script>
</body>

 拖拽_02 正方形碰撞检测

var last = str[str.length - 1];
for(var i = 0; i < str.length - 1; i++) {
    //碰撞检测
    if(last.x + last.w >= str[i].x //左
    &&
    last.y + last.h >= str[i].y //上
    &&
    str[i].x + str[i].w >= last.x //右
    &&
    str[i].y + str[i].h >= last.y //下
    ){
        str[i].fillstyle = "red";
    }else{
        str[i].fillstyle = "blue";
    }
}

拖拽_03 圆形碰撞检测

var last = str[str.length - 1];
for(var i = 0; i < str.length - 1; i++) {
//碰撞检测
if(Math.pow(last.x - str[i].x, 2) + Math.pow(last.y - str[i].y, 2) < Math.pow(str[i].r + last.r, 2)){
    str[i].fillstyle = "red";
}else{
    str[i].fillstyle = "blue";
}
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值