最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Creating new fabric canvas changes canvas position - Stack Overflow

programmeradmin0浏览0评论

I am trying to learn about fabricjs and noticed that when i create a new fabric.Canvas object it changes the position of my canvas.

HTML

<canvas id="c"></canvas>

Css

#c {
border: thin red solid;
      position: absolute;
      top: 50px;
      left: 100px;
}

Javascript

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

var img = new Image();
img.src = 'cheese.jpg';
img.onload = function() {
   ctx.drawImage(img, 0, 0);  
};

// applying the below line shifts the canvas element back to 0,0 position
var cFabric = new fabric.Canvas('c');

Hoping you guys know what i am doing wrong.

I am trying to learn about fabricjs and noticed that when i create a new fabric.Canvas object it changes the position of my canvas.

HTML

<canvas id="c"></canvas>

Css

#c {
border: thin red solid;
      position: absolute;
      top: 50px;
      left: 100px;
}

Javascript

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

var img = new Image();
img.src = 'cheese.jpg';
img.onload = function() {
   ctx.drawImage(img, 0, 0);  
};

// applying the below line shifts the canvas element back to 0,0 position
var cFabric = new fabric.Canvas('c');

Hoping you guys know what i am doing wrong.

Share Improve this question asked Apr 25, 2016 at 11:06 AeseirAeseir 8,45412 gold badges62 silver badges125 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 6

You are not doing anything wrong. Calling the fabric.Canvas constructor on your native canvas element will result in your native canvas getting wrapped by a .canvas-container div. The original canvas gets an added .lower-canvas class and its left, right css styles are set to 0px. Other then that, a sibling canvas is added below your original canvas, with a class of upper-canvas. These two canvases act like layers, managed by the inner workings of Fabric.js (magic :O).

If you need to position and style your canvas, I remend you wrap your html canvas with a wrapper div.

<div id="canvas-wrapper">
    <canvas id="c"></canvas>
</div>

Next transfer your css rules to the wrapper

#canvas-wrapper {
  position: absolute;
  top: 50px;
  left: 100px;
}

Here's a simple fiddle that I made by updating @Mullainathan's sample fiddle: https://jsfiddle/eo7vdg1t/1/

发布评论

评论列表(0)

  1. 暂无评论