如何使画布响应

时间:2015-07-13 22:05:35

标签: javascript jquery angularjs html5-canvas materialize

我正在使用console.image的一个演示来制作一个简单的模因生成器。我很难让它变得敏感。我已经做了一些搜索,但我没有得到充分告诉我如何做的例子。我做了一个plu ..我正在使用angular / materialize / console.image

plunker

  <body ng-controller="AppCtrl as appCtrl">
<div class="container">
  <div class="row">
    <div class="col s6 offset-s3 z-depth-4">
      <div class="card-panel teal">
        <div class="row">
          <div class="col s12">
            <div class="card-panel teal canvas"></div>
          </div>
          <div class="row">
            <div class="input-field col s12">
              <select class="browser-default" ng-model="selectedMeme" ng-init="selectedMeme = memes[0]" ng-change="alterMeme()" ng-options="m.name for m in memes"></select>
            </div>
          </div>
          <div class="row">
            <div class="input-field col s6">
              <input type="text" placeholder="" id="top_text" class="validate" ng-model="toptext" ng-change="alterMeme()" />
              <label for="top_text">Top Text</label>
            </div>
            <div class="input-field col s6">
              <input type="text" id="bottom_text" class="validate" ng-model="bottomtext" ng-change="alterMeme()" />
              <label for="bottom_text">Bottom Text</label>
            </div>
          </div>
          <div class="row">
            <div class="input-field col s12">
              <a class="waves-effect waves-light btn" ng-click="create()">
                <i class="material-icons left"></i>

                Save Image</a>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

console.image.js

(function(console) {
"use strict";

//Bootlegged of imgur.com/memegen
var memes = {
    "Rudy": "http://i.imgur.com/1nJv40n.jpg"
};

var canvas = document.createElement("canvas");
console.list = memes;

function drawMemeText(ctx, type, text, width, y) {
    text = text.toUpperCase();
    //Determine the font size
    if (text.length < 24) {
        var val = Math.max(0, text.length - 12),
            size = 70 + (val * -3);

        drawText(ctx, size, text, width / 2, y);
    } else if (text.length < 29) {
        drawText(ctx, 40, text, width / 2, y);
    } else {
        var strs = wrap(text, 27);
        strs.forEach(function (str, i) {
            drawText(ctx, 40, str, width / 2, (type == "lower") ? (y - ((strs.length - 1) * 40)) + (i * 40) : y + (i * 40));
        });
    }
}

function drawText(ctx, size, text, x, y) {
    //Set the text styles
    ctx.font = "bold " + size + "px Impact";
    ctx.fillStyle = "#fff";
    ctx.textAlign = "center";
    ctx.textBaseline = "middle";
    ctx.lineWidth = 7;
    ctx.strokeStyle = "#000";
    ctx.strokeText(text, x, y);
    ctx.fillText(text, x, y);
}
function wrap(text, num) {
    var output = [],
        split = text.split(" ");

    var str = [];
    for (var i = 0, cache = split.length; i < cache; i++) {
        if ((str + split[i]).length < num) str.push(split[i])
        else {
            output.push(str.join(" "));
            str.length = 0;
            str.push(split[i]);
        }
    }

    //Push the final line
    output.push(str.join(" "));

    return output;
}
console.meme = function (upper, lower, image, width, height) {
    if (!upper && !lower && !image) return console.log("> " + Object.keys(memes).join("\n> "));


    var ctx = canvas.getContext("2d"),
    width = width || 500,
    height = width || 500,
    //I tweaked it at these dimensions,
    //So everything scales from here
    _w = 500, _h = 500;

    ctx.clearRect(0, 0, width, height);

    var img = new Image();
    img.setAttribute('crossOrigin', 'anonymous');
    img.onload = function () {
        canvas.width = width;
        canvas.height = height;

        var text = upper.toUpperCase();

        ctx.scale(width / 500, height / 500);

        //Draw the background
        ctx.drawImage(this, 0, 0, _w, _h);

        drawMemeText(ctx, "upper", upper, _w, 50); //upper
        drawMemeText(ctx, "lower", lower, _w, _h - 50); //upper

        //my lil' hack
        canvas.id = 'myCanvas';
        $('.canvas').html(canvas);

    };

    if (memes[image]) var url = memes[image];
    else var url = image;

    img.src = url; //"http://www.corsproxy.com/" + url.replace(/https?:\/\//, "");
   };
 })(console);

app.js

angular.module('scottMeme', [])
 .controller('AppCtrl', function ($scope) {

$scope.toptext = '';
$scope.bottomtext = '';
$scope.selectedMeme = 'Rudy';
$scope.memes = [];

for (var key in console.list) {
    $scope.memes.push({ name: key, url: console.list[key] });
}

$scope.alterMeme = function () {
    var url = $scope.memes[$scope.memes.indexOf($scope.selectedMeme)].name;
    console.meme($scope.toptext, $scope.bottomtext, url);
}

$scope.create = function () {
    var uri = document.getElementById('myCanvas').toDataURL();
    downloadImage(uri, generateName());
}

function generateName() {
    var n = [];
    for (var i = 0; i < 10; i++) {
        n.push((Math.floor(Math.random() * 16)).toString(16));
    }
    return n.join('');
};

function downloadImage(uri, name) {
    var link = document.createElement('a');
    link.download = name;
    link.href = uri;
    link.click();
    };
  }).run(function () {
   console.meme('', '', 'Rudy');
});

2 个答案:

答案 0 :(得分:2)

尝试在css中设置#myCanvas { width: 100%; }

答案 1 :(得分:0)

为canvas标记设置特殊/修复维度 而这个代码用于半响应画布元素

/*jshint strict:true, es5:true, forin:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, strict:true, undef:true, unused:true, nonew:true, browser:true, devel:true, indent:2, boss:true, curly:false, immed:false, latedef:true, newcap:true, plusplus:false, trailing:true, maxparams:4, maxerr:100, debug:false, asi:false, evil:false, expr:true, eqnull:false, esnext:false, funcscope:false, globalstrict:false, loopfunc:false */
(function(pageWidth,pageHeight,px,py){
  "use strict";
  var prefix='',
  iv = 0,
  vendors = {Webkit: 'webkit', Moz: '', O: 'o', ms: 'MS' },
  testEl = document.createElement('div'),
  each = function(elements, callback){
    for (var key in elements)
      if (callback.call(elements[key], key, elements[key]) === false) return elements;
    return elements;
  },
  winZoom = function(){
    var paddingX = px || 0,
      paddingY = py || 0,
      winHeight  = winHeight || window.innerHeight,
      winWidth  = winWidth || window.innerWidth,
      container = document.querySelector('.container'),
      scalex = Math.floor((winHeight-paddingY)/pageHeight*1000)/1000,
      scaley = Math.floor((winWidth-paddingX)/pageWidth*1000)/1000,
      scale = Math.min(scalex,scaley),
      top = Math.round((winHeight-pageHeight*scale)/2),
      left = Math.round((winWidth-pageWidth*scale)/2);
    left = left>0 ? left : 0;
    container.style.position  = 'absolute';
    container.style.left = left + 'px';
    container.style.top = top + 'px';
    container.style[prefix+'TransformOrigin']= "0 0";
    container.style[prefix+'Transform'] = 'scale('+scale+')';
  },
  resize=function(){
    if(iv) clearTimeout(iv);
    iv = setTimeout(winZoom,300);
  };

  each(vendors, function(vendor, evt){
    if (testEl.style[vendor + 'TransitionProperty'] !== undefined) {
      prefix = vendor;
      return false;
    }
  });

  window.onresize = resize;

  winZoom();
})(900,500,30,30);

和html文件中的示例

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" />
  <title>Document</title>
  <style type="text/css">
    html,body{
      height: 100%;
      width: 100%;
      padding: 0;
      margin: 0;
      overflow: hidden;
    }
    body{
      padding-top: 1px;
      overflow: hidden;
    }
    .container{
      width: 900px;
      height: 500px;
      background-color: hsl(60,20%,80%);
      margin: 0 auto;
      -webkit-transition: all 400ms;
      -moz-transition: all 400ms;
      -ms-transition: all 400ms;
      -o-transition: all 400ms;
      transition: all 400ms;
    }
  </style>
</head>
<body>
  <div class="container"></div>
  <script type="text/javascript" src="fix_zoom.min.js"></script>
</body>
</html>

有关详细信息,请查看我的要点:https://gist.github.com/AliMD/5099197
演示:http://jsbin.com/mikaqa/1