HTML5 Canvas使用貝玆曲線的範例
這邊我寫了一個簡單的Javascript搭配了HTML5的Canvas使用了貝玆曲線的範例,
但寫的有點亂,但是我簡單講解一下這個程式主要目的在做什麼。
我會在body的標籤中建立一個canvas id='b' 寬度為785,長度為180並且在canvas中畫了一條線,當我滑鼠按下左鍵沒有放開的時候,線會跟著滑鼠而彎曲反之放開之後就固定住。
對了我有用到JQuery的library,再測試這個Code的時候記的要加上去。
對了我有用到JQuery的library,再測試這個Code的時候記的要加上去。
- window.draw_line =
- {
- canvas : null,
- context : null,
- mouse_hold : false
- };
- function TextInit(context){
- var my_gradient = context.createLinearGradient(0, 0, 0, 225);
- my_gradient.addColorStop(0, "white");
- context.fillStyle = my_gradient
- context.font = "bold 20px sans-serif";
- };
- $(document).ready(function() {
- draw_line.canvas = document.getElementById("b");
- draw_line.context = draw_line.canvas.getContext("2d");
- TextInit(draw_line.context);
- var controlX1 = 0;
- var controlY1 = 10;
- var controlX2 = 0;
- var controlY2 = 10;
- var endX = 785;
- var endY = 90;
- // drww line
- draw_line.context.beginPath();
- draw_line.context.moveTo(0, 90);
- draw_line.context.lineTo(785, 90);
- draw_line.context.lineWidth = 5;
- draw_line.context.strokeStyle = "#000";
- draw_line.context.stroke();
- $("#b").mousemove(function(e){
- if (draw_line.mouse_hold)
- {
- var offset_left = $("#b").offset().left;
- var offset_top = $("#b").offset().top;
- //javascript: console.log( , );
- draw_line.context.clearRect(0 ,0, 785, 785);
- //Draw mouse position on canvas
- draw_line.context.beginPath();
- draw_line.context.moveTo(0, 90);
- draw_line.context.fillText((e.clientX- offset_left) +",", 0, 30);
- draw_line.context.fillText((e.clientY - offset_top), 80, 30);
- controlX1 = (e.clientX - offset_left)-10;
- controlX2 = (e.clientX - offset_left)+10;
- controlY1 = (e.clientY - offset_top);
- controlY2 = (e.clientY - offset_top);
- draw_line.context.bezierCurveTo(controlX1, controlY1, controlX2, controlY2, endX, endY);
- //Debug information
- javascript: console.log( controlX1, controlX2);
- javascript: console.log( controlY1, controlY2);
- draw_line.context.stroke();
- }
- }).mousedown(function(){
- draw_line.mouse_hold = true;
- }).bind('mouseup mouseout',function(){
- draw_line.mouse_hold = false;
- });
- });
留言