DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> HTML基礎知識 >> HTML5教程
HTML5 Canvas 自由拼圖實作:拖曳、旋轉、縮放與上傳合成
編輯:HTML5教程     

這個拼圖元件示範了 Canvas 上做「物件操作」的完整套路:左側選圖、右側拼放,每張圖都能拖曳移動、拉角縮放、旋轉,還能刪除、替換,最後把整個畫布合成一張圖上傳。原始碼拆成 canvasElement.js(畫布管理)、canvasImg.js(單張圖的幾何計算)與 puzzle.html 三個部分。

canvasElement.js:畫布與事件調度

這個模組負責三件事:維護圖片陣列、判斷滑鼠點到哪張圖或哪個控制角、以及重新渲染。

define('canvasElement', ['../multi_upload/core'], function (S) {
var Canvas = window.Canvas || {};
(function () {

Canvas.Element = function () {};

Canvas.Element.prototype.fillBackground = true;
Canvas.Element.prototype.showcorners = false;
Canvas.Element.prototype.photoborder = true;
Canvas.Element.prototype.polaroid = false;
Canvas.Element.prototype._backgroundImg = null;
Canvas.Element.prototype._aImages = null;
Canvas.Element.prototype._oContext = null;
Canvas.Element.prototype._oElement = null;
Canvas.Element.prototype._oConfig = null;
Canvas.Element.prototype._currentTransform = null;
Canvas.Element.prototype._prevTransform = null;
Canvas.Element.prototype.curAngle = null;

Canvas.Element.prototype.init = function (el, oConfig) {
    if (el == '') { return; }
    this._initElement(el);
    this._initConfig(oConfig);
    this._createCanvasBackground();   // 底圖層
    this._createContainer();          // 圖片層
    this._initEvents();
    this._initCustomEvents();
};

Canvas.Element.prototype._initElement = function (el) {
    this._oElement = document.getElementById(el);
    this._oContextTop = this._oElement.getContext('2d');   // 最上層(拖曳中的圖)
};

Canvas.Element.prototype._initConfig = function (oConfig) {
    this._oConfig = oConfig;
    this._oElement.width = this._oConfig.width;
    this._oElement.height = this._oConfig.height;
    this._oElement.style.width = this._oConfig.width + 'px';
    this._oElement.style.height = this._oConfig.height + 'px';
};

Canvas.Element.prototype._initEvents = function () {
    var _this = this;
    S(this._oElement).on('mousedown', function (e) { _this.onMouseDown(e); });
    S(this._oElement).on('mouseup',   function (e) { _this.onMouseUp(e); });
    S(this._oElement).on('mousemove', function (e) { _this.onMouseMove(e); });
};

Canvas.Element.prototype._initCustomEvents = function () {
    this.onRotateStart    = new Canvas.CustomEvent('onRotateStart');
    this.onRotateMove     = new Canvas.CustomEvent('onRotateMove');
    this.onRotateComplete = new Canvas.CustomEvent('onRotateComplete');
    this.onDragStart      = new Canvas.CustomEvent('onDragStart');
    this.onDragMove       = new Canvas.CustomEvent('onDragMove');
    this.onDragComplete   = new Canvas.CustomEvent('onDragComplete');
};

Canvas.Element.prototype.setCanvasBackground = function (oImg) {
    this._backgroundImg = oImg;
    var s = oImg.getOriginalSize();
    this._oContextBackground.drawImage(oImg._oElement, 0, 0, s.width, s.height);
};

滑鼠按下:決定要拖曳還是旋轉

Canvas.Element.prototype.onMouseDown = function (e) {
    var mp = this.findMousePosition(e);
    if (this._currentTransform != null || this._aImages == null) { return; }

    var oImg = this.findTargetImage(mp, false);
    if (!oImg) {
        this._groupSelector = { ex: mp.ex, ey: mp.ey, top: 0, left: 0 };
    } else {
        // 點到四角 → 旋轉;點到內部 → 拖曳
        var action = (!this.findTargetCorner(mp, oImg)) ? 'drag' : 'rotate';
        this._prevTransform = this._currentTransform = {
            target: oImg,
            action: action,
            scalex: oImg.scalex,
            offsetX: mp.ex - oImg.left,
            offsetY: mp.ey - oImg.top,
            ex: mp.ex, ey: mp.ey,
            left: oImg.left, top: oImg.top,
            theta: oImg.theta
        };
        this.renderAll(false, false);
    }
};

Canvas.Element.prototype.onMouseMove = function (e) {
    var mp = this.findMousePosition(e);
    if (this._aImages == null) { return; }

    if (this._currentTransform == null) {
        this.setCursor(mp, this.findTargetImage(mp, true));
    } else if (this._currentTransform.action == 'rotate') {
        this.rotateImage(mp);
        this.scaleImage(mp);        // 旋轉時同時處理縮放
        this.onRotateMove.fire(e);
    } else {
        this.translateImage(mp);
        this.onDragMove.fire(e);
    }
    this.renderTop();
};

Canvas.Element.prototype.onMouseUp = function (e) {
    if (this._aImages == null) { return; }
    if (this._currentTransform != null && this._currentTransform.action == "rotate") {
        this.onRotateComplete.fire(e);
    } else if (this._currentTransform != null && this._currentTransform.action == "drag") {
        this.onDragComplete.fire(e);
    }
    this._currentTransform = null;
    this.renderTop();
};

旋轉與縮放的數學

旋轉靠 atan2 求兩次角度差;縮放靠兩點到中心的距離比值。

Canvas.Element.prototype.rotateImage = function (mp) {
    var lastAngle = Math.atan2(
        this._currentTransform.ey - this._currentTransform.top,
        this._currentTransform.ex - this._currentTransform.left);
    var curAngle = Math.atan2(
        mp.ey - this._currentTransform.top,
        mp.ex - this._currentTransform.left);
    this._currentTransform.target.theta =
        (curAngle - lastAngle) + this._currentTransform.theta;
    this.curAngle = this._currentTransform.target.theta * 180 / 3.14;
};

Canvas.Element.prototype.scaleImage = function (mp) {
    var lastLen = Math.sqrt(
        Math.pow(this._currentTransform.ey - this._currentTransform.top, 2) +
        Math.pow(this._currentTransform.ex - this._currentTransform.left, 2));
    var curLen = Math.sqrt(
        Math.pow(mp.ey - this._currentTransform.top, 2) +
        Math.pow(mp.ex - this._currentTransform.left, 2));
    var curScale = this._currentTransform.scalex * (curLen / lastLen);
    if (curScale > 0.7) {                     // 下限,避免縮到看不見
        this._currentTransform.target.scalex = curScale;
        this._currentTransform.target.scaley = curScale;
    }
};

實際畫圖

Canvas.Element.prototype.drawImageElement = function (context, oImg, allowCorners) {
    oImg.cornervisibility = allowCorners;
    var offsetY = oImg.height / 2;
    var offsetX = oImg.width / 2;

    context.save();
    context.translate(oImg.left, oImg.top);   // 移到圖中心
    context.rotate(oImg.theta);               // 旋轉
    context.scale(oImg.scalex, oImg.scaley);  // 縮放
    this.drawBorder(context, oImg, offsetX, offsetY);

    var s = oImg.getOriginalSize();
    context.drawImage(oImg._oElement, -s.width / 2, -s.height / 2, s.width, s.height);

    if (oImg.cornervisibility) {
        this.drawCorners(context, oImg, offsetX, offsetY);
    }
    context.restore();                        // 還原座標系,影響不到下一張
};

輸出成圖檔

Canvas.Element.prototype.canvasTo = function (format) {
    this.renderAll(true, false);
    var containerCanvas = this._oContextTop;
    for (var i = 0, l = this._aImages.length; i < l; i += 1) {
        this.clearCorners(containerCanvas, this._aImages[i],
                          this._aImages[i].width / 2, this._aImages[i].height / 2);
    }
    if (format == 'jpeg' || format == 'png') {
        return this._oElement.toDataURL('image/' + format);
    }
};

}());
return Canvas;
});

注意輸出前先把四角的控制點清掉,否則那些綠色小方塊會一起被存進圖片裡。

canvasImg.js:單張圖的座標計算

這個模組負責把「中心座標 + 旋轉角度 + 縮放比例」換算成四個角的實際座標,供 hit test 使用。

define('canvasImg', ['../multi_upload/core'], function (S) {
var Canvas = window.Canvas || {};
(function () {

Canvas.Img = function (el, oConfig) {
    this._initElement(el);
    this._initConfig(oConfig);
    this.setImageCoords();
};

var DEFAULT_CONFIG = {
    "TOP":     { key: "top",      value: 10 },
    "LEFT":    { key: "left",     value: 10 },
    "ANGLE":   { key: "angle",    value: 0 },
    "THETA":   { key: "theta",    value: 0 },
    "SCALE-X": { key: "scalex",   value: 1 },
    "SCALE-Y": { key: "scaley",   value: 1 },
    "CORNERSIZE":   { key: "cornersize",   value: 10 },
    "BORDERWIDTH":  { key: "borderwidth",  value: 10 },
    "POLAROIDHEIGHT": { key: "polaroidheight", value: 40 },
    "RANDOMPOSITION": { key: "randomposition", value: true }
};

Canvas.Img.prototype.setImageCoords = function () {
    this.left = parseInt(this.left);
    this.top = parseInt(this.top);
    this.currentWidth = parseInt(this.width) * this.scalex;
    this.currentHeight = parseInt(this.height) * this.scalex;

    // 半對角線長與對角角度,用來推出旋轉後的左上角
    this._hypotenuse = Math.sqrt(Math.pow(this.currentWidth / 2, 2) +
                                 Math.pow(this.currentHeight / 2, 2));
    this._angle = Math.atan(this.currentHeight / this.currentWidth);

    var offsetX = Math.cos(this._angle + this.theta) * this._hypotenuse;
    var offsetY = Math.sin(this._angle + this.theta) * this._hypotenuse;

    var theta = this.theta;
    var sinTh = Math.sin(theta);
    var cosTh = Math.cos(theta);

    var tl = { x: this.left - offsetX, y: this.top - offsetY };
    var tr = { x: tl.x + this.currentWidth * cosTh,
               y: tl.y + this.currentWidth * sinTh };
    var br = { x: tr.x - this.currentHeight * sinTh,
               y: tr.y + this.currentHeight * cosTh };
    var bl = { x: tl.x - this.currentHeight * sinTh,
               y: tl.y + this.currentHeight * cosTh };

    this.oCoords = { tl: tl, tr: tr, br: br, bl: bl };
    this.setCornerCoords();
};

}());
return Canvas;
});

puzzle.html:頁面結構

<div id='html5_puzzle'>
  <div id='puzzle_left'>
    <div class='puzzle_column'>
      <ul>
        <li><img src='small_img/1.jpg' data-index='1' /></li>
        <li><img src='small_img/2.jpg' data-index='2' /></li>
        <!-- ... -->
      </ul>
    </div>
    <div class='puzzle_column'><!-- 第二欄 --></div>
  </div>

  <div id='puzzle_right'>
    <div id='puzzle_canvas'>
      <canvas id="canvid1"></canvas>
      <div id='canvas_menu'>
        <a href='javascript:void(0)' id='photo_delete'>刪除</a>
        <a href='javascript:void(0)' id='photo_update'>更改圖片</a>
      </div>
    </div>
    <img id="bg" src="big_img/1.jpg" width="600" height="450" />
  </div>

  <div id='puzzle_bottom'>
    <a href='javascript:void(0)' id='add_img'>
      <span>添加圖片</span><input type="file" multiple="" id="fileImage">
    </a>
    <a href='javascript:void(0)' id='upload_btn'>上傳</a>
    <a>點擊圖片可以旋轉、拖曳、縮放</a>
  </div>
</div>

這裡有兩個 canvas 是隱藏用的輔助元素:#test_canvas 用來把上傳的圖先縮圖並轉成 dataURL,#bg 則是承載拼圖底圖的 img。實際顯示的是 #canvid1 加上程式動態產生的兩個 canvas 層。

互動邏輯

require(['img_upload', '../puzzle/canvasImg', '../puzzle/canvasElement'],
function (S, canvasImg, canvasElement) {

var img = [];
var canvas = new canvasElement.Element();
canvas.init('canvid1', { width: 600, height: 450 });

// 點左側縮圖 → 換底圖
S('.puzzle_column img').on('click', function (e) {
    var index = this.getAttribute('data-index');
    $('bg').onload = function () {
        var ctx = $('canvid1-canvas-background').getContext('2d');
        ctx.clearRect(0, 0, 600, 450);
        img[0] = new canvasImg.Img($('bg'), {});
        canvas.setCanvasBackground(img[0]);
    };
    $('bg').setAttribute('src', 'medium_img/' + index + '.jpg');
    e.stopPropagation();
});

// 刪除目前選取的圖
S('#photo_delete').on('click', function () {
    var i = getCurImg();
    canvas._aImages.splice(i, 1);
    canvas.renderAll(true, true);
    $('canvas_menu').style.display = "none";
});

// 上傳:把 canvas 內容轉成 dataURL 後 POST
S('#upload_btn').on('click', function () {
    var imgData = canvas.canvasTo('jpeg');
    S.ajax({
        url: '/upload1.php',
        type: 'POST',
        data: { imgData: imgData.substr(22), file_name: 'mix_img.jpeg' },
        dataType: 'text',
        success: function (data) { alert("上傳完成"); }
    });
});
});

本機圖片的處理走 FileReader:readAsDataURL(file) 讀成 dataURL,指派給一個暫時 Image,等 onload 後縮圖(限制在 200px 內)畫進隱藏的 #test_canvas,再用 toDataURL 轉成的字串塞進 #canvid1 成為新的一張可拖曳圖片。

這個實作值得學與不建議照抄的地方

值得學的是三層 canvas 的分層思路:底圖層、圖片層、最上層(拖曳中的物件)。這樣拖曳時只需重繪最上層,不必把全部圖片重畫一遍,效能比「每次 renderAll」好得多。

另一個可借鏡之處是用 save/restore 隔離每張圖的變換。每張圖有自己的 translate、rotate、scale,若不用 save/restore 包住,變換矩陣會互相污染,這是 Canvas 物件化開發最常踩的坑。

但不建議照抄的部分也不少:程式碼大量直接存取 canvas._aImages、canvas._prevTransform 這些底層屬性,把 hit test 與渲染邏輯散落在頁面層,維護性很差;Math.PI 被寫成 3.14,會累積誤差;縮放沒有 upper bound,可以無限放大;上傳的 substr(22) 是硬寫死的 dataURL 前綴長度,換成 png 就會出錯,正確做法是用正則把 data:image/...;base64, 整段去掉。

如果今天要重做同樣的功能,比較務實的選擇是直接用成熟函式庫:Fabric.js 或 Konva 都已經把物件 selection、旋轉縮放控制點、hit test、序列化、縮放與拖拉的邊界處理做好了,能省下這份程式碼裡九成的樣板。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved