Canvas對象繞任意點作爲中心旋轉

Canvas對象繞任意點作爲中心旋轉

對象繞自己中心旋轉

效果:

代碼:

           //---sample rotate  center
            var width  = 100
            var height = 100
            var x      = (canvas.width-width)*0.5	//形狀放置在畫布中心
            var y      = (canvas.height-height)*0.5	//形狀放置在畫布中心
            var cx     = x + 0.5 * width   			// cx 形狀中心
            var cy     = y + 0.5 * height  			// cy 形狀中心
			
			//--清空之前的繪製
			ctx.clearRect(0, 0, canvas.width, canvas.height)
			
            ctx.fillStyle = "#ff0000"
            ctx.fillRect(x, y, width, height)  			//沒旋轉之前的形狀

            ctx.translate(cx, cy)              			//座標圓點設置到形狀中心
            ctx.rotate( (Math.PI / 180) * 45)  			//旋轉 45 度
            ctx.translate(-cx, -cy)           			//座標圓點重置到 0,0

            ctx.fillStyle = "#0000ff"
            ctx.fillRect(x, y, width, height)			//沒旋轉之後的形狀

對象繞任意中心旋轉

效果:

代碼:

            var width  = 100
            var height = 100
            
            //--形狀位置
            var x      = 256                        //形狀放置x=256
            var y      = 150                        //形狀放置y=150
            
            //--任意中心
            var cx     = canvas.width*0.5           //旋轉中心=畫布中心
            var cy     = canvas.height*0.5          //旋轉中心=畫布中心
            
			//--清空之前的繪製
            ctx.clearRect(0, 0, canvas.width, canvas.height)
            
            ctx.fillStyle = "#ff0000"
            ctx.fillRect(x, y, width, height)  			//沒旋轉之前的形狀

            ctx.translate(cx, cy)              			//座標圓點設置到旋轉中心
            ctx.rotate( (Math.PI / 180) * 45)   		//旋轉 45 度
            ctx.translate(-cx, -cy)           			//座標圓點重置到 0,0		

            ctx.fillStyle = "#0000ff"
            ctx.fillRect(x, y, width, height)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章